package com.bawei.day12_broadcastrecevier;

import androidx.appcompat.app.AppCompatActivity;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.view.View;
import android.widget.Toast;

/**
 有序广播：一个发送方+多个接收方
 sendOrderedBroadcast（）
 优先级setPriority ，优先级越高 越先接受
 abortBroadcast();//中断广播，其他接受者不能接受到

 */
public class Main3Activity extends AppCompatActivity {
    private MyOrderRecevicer myOrderRecevicer;
    private MyOrderRecevicer2 myOrderRecevicer2;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main3);
        myOrderRecevicer = new MyOrderRecevicer();
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.setPriority(300);//设置优先级 -1000 到 1000
        intentFilter.addAction("com.bawei.youxu");
        registerReceiver(myOrderRecevicer,intentFilter);

        myOrderRecevicer2 = new MyOrderRecevicer2();
        IntentFilter intentFilter2 = new IntentFilter();
        intentFilter2.setPriority(500);//设置优先级 -1000 到 1000
        intentFilter2.addAction("com.bawei.youxu");
        registerReceiver(myOrderRecevicer2,intentFilter2);


        //发送普通广播
        findViewById(R.id.send).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent();
                intent.setAction("com.bawei.youxu");
                sendBroadcast(intent);
            }
        });

        findViewById(R.id.send_sort).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent();
                intent.setAction("com.bawei.youxu");
                sendOrderedBroadcast(intent,null); //发送有序广播

            }
        });
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        unregisterReceiver(myOrderRecevicer);
        unregisterReceiver(myOrderRecevicer2);
    }

    class MyOrderRecevicer extends BroadcastReceiver{

        @Override
        public void onReceive(Context context, Intent intent) {
            if("com.bawei.youxu".equals(intent.getAction())){
                Toast.makeText(context, "1111", Toast.LENGTH_SHORT).show();
            }

        }
    }

    class MyOrderRecevicer2 extends BroadcastReceiver{

        @Override
        public void onReceive(Context context, Intent intent) {
            if("com.bawei.youxu".equals(intent.getAction())){
                Toast.makeText(context, "22222", Toast.LENGTH_SHORT).show();
                abortBroadcast();//中断广播，其他接受者不能接受到
            }

        }
    }

}
